package util

import (
    "crypto/md5"
    "fmt"
    "crypto/aes"
    "crypto/cipher"
    "encoding/hex"
)


type Secret struct {
    CommonIV    []byte
    Key         string
    Block       cipher.Block
}

func NewSecret(key string) *Secret {
    s := new(Secret)
    s.Key = fmt.Sprintf("%x", md5.Sum([]byte(key)))
    s.CommonIV = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}

    s.Block, _ = aes.NewCipher([]byte(s.Key))
    return s
}

func (this *Secret) Encryption(s string) string {
    //加密字符串
    plaintext := []byte(s)
    cfb := cipher.NewCFBEncrypter(this.Block, this.CommonIV)
    ciphertext := make([]byte, len(plaintext))
    cfb.XORKeyStream(ciphertext, plaintext)
    result := fmt.Sprintf("%x", ciphertext)
    return result
}

func (this *Secret) Decryption(s string) string {
    // 解密字符串
    ciphertext, _ := hex.DecodeString(s)
    cfbdec := cipher.NewCFBDecrypter(this.Block, this.CommonIV)
    plaintextCopy := make([]byte, len(ciphertext))
    cfbdec.XORKeyStream(plaintextCopy, ciphertext)
    result := fmt.Sprintf("%s", plaintextCopy)
    return result
}



